package com.open.capacity.finance.util;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.open.capacity.reptile.constant.GDSZCZConstant;
import com.open.capacity.reptile.dto.gdszcz.request.CommonRequest;
import com.open.capacity.reptile.dto.gdszcz.request.TokenRequest;
import com.open.capacity.reptile.dto.gdszcz.response.CommonResponse;
import com.open.capacity.reptile.util.HttpUtils;
import com.open.capacity.user.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.MessageFormat;

@Slf4j
@Component
public class GDSZCZUtils {

    @Autowired
    private SysConfigService configService;

    /**
     * 获取header
     *
     * @return
     */
    public Header[] packetHeaders() {
        Header[] headers = new Header[1];
        headers[0] = new BasicHeader("X-Aa-Token", getToken());
        return headers;
    }

    public CommonRequest packetRequest(String agencyCode, Integer fiscalYear, String updateStartTime, String dtgCode) {
        CommonRequest request = new CommonRequest();
        request.setDtgCode(dtgCode);
        request.setFiscalYear(fiscalYear);
        request.setMofDivCode(configService.findByKey("gdszcz_mofDivCode").getCnfValue());
        request.setUserName(configService.findByKey("gdszcz_userName").getCnfValue());
        request.setUserPass(configService.findByKey("gdszcz_userPass").getCnfValue());
        request.setUserType(configService.findByKey("gdszcz_userType").getCnfValue());
        request.setAgencyCode(agencyCode);
        //requestVoucherPay.setUpdateStartTime(System.currentTimeMillis() / 1000);
        request.setUpdateStartTime(updateStartTime);

        return request;
    }

    /**
     * 获取token
     *
     * @return
     */
    public String getToken() {
        String token = null;
        TokenRequest requestToken = new TokenRequest();
        requestToken.setAppId(configService.findByKey("gdszcz_appid").getCnfValue());
        requestToken.setSecret(configService.findByKey("gdszcz_secret").getCnfValue());
        String responseToken = null;
        try {
            responseToken = HttpUtils.requestForJson(MessageFormat.format(GDSZCZConstant.gettoken_url, configService.findByKey("gdszcz_apiurl").getCnfValue()), JSONObject.toJSONString(requestToken), new Header[0]);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }

        CommonResponse<String> responseTokenData = JSONObject.parseObject(responseToken, new TypeReference<CommonResponse<String>>() {
        });

        if (responseTokenData.getResultCode().equals("000")) {
            token = responseTokenData.getData();
        }
        return token;
    }

}
